package com.myapp.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

public class CommUtil {

	/**
	 * 判断传入的参数是否为null或空字符串或全部为空格
	 * */
	public static boolean isBlank(String s) {
		if (s == null || s.length() == 0 || s.trim().length() == 0)
			return true;
		else
			return false;
	}

	/**
	 * 若参数为空，返回空字符串
	 * */
	public static String isNull(String o) {
		return o == null ? "" : o;
	}

	/**
	 * @return (00000000+str)返回包括报文长度的字符串
	 * @param str
	 *            action中返回的字符串
	 * @param len
	 *            表示JSON前面的8位的"报文长度"
	 * */
	public static String countRtnByte(String str, int len) {
		System.out.println(">>>>>>>>不包含00000000:" + str);
		byte[] byteStr = null;
		try {
			byteStr = str.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			System.out.println("字符串不是UTF-8编码格式");
			e.printStackTrace();
		}

		int length = byteStr.length;// 报文体长度
		int lengthTotal = length + len;// 报文总长度

		String add0Str = addStr(lengthTotal + "", len);
		return add0Str + str;
	}

	/**
	 * 读取Properties属性文件:
	 * fileName是以src为根目录的文件名称,例:src/config/deal/dealConfig.properties
	 * */
	public static Properties parseProperties(Class<?> inputClass,
			String fileName) {
		System.out.println("文件名称是:" + fileName);
		Properties props = new Properties();

		// method one
		// String path =
		// inputClass.getClass().getResource("/").getPath().substring(1);
		// String filePath = path.substring(0, (path.length() - 4)) + fileName;

		// method two
		String filePath = System.getProperty("user.dir").toString() + fileName;

		System.out.println("文件路径是:" + filePath);

		try {
			props.load(new FileInputStream(filePath));
		} catch (FileNotFoundException e) {
			System.out.println("/CommonUtil/parseProperties 异常:"
					+ e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("/CommonUtil/parseProperties 异常:"
					+ e.getMessage());
			e.printStackTrace();
		}
		return props;
	}

	/**
	 * 补齐len位,不足左补0
	 * */
	public static String addStr(String str, int len) {
		String strRtn = "";
		for (int i = 0; i < (len - str.length()); i++) {
			strRtn += "0";
		}
		strRtn = strRtn + str;
		return strRtn;
	}

	/**
	 * 构建json字符串
	 * 
	 * @param transCode
	 *            交易码
	 * @param sysuserid
	 *            操作人ID
	 * @param pageModel
	 *            报文体Model
	 * @return
	 */
	public static String constructJsonStr(String transCode, String sysuserid,
			Map<String, Object> pageModel) throws Exception {
		// 系统时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
		String sysdate = sdf.format(new Date());

		pageModel.put("iface", transCode);
		pageModel.put("sysuserid", sysuserid);
		pageModel.put("sysdate", sysdate);

		return JsonUtil.getJsonStringFromMap(pageModel);
	}

	// /**
	// * 把传入的对象转成json
	// * */
	// public static String createJson(Object obj) throws Exception {
	// ObjectMapper objectMapper = new ObjectMapper();
	// return objectMapper.writeValueAsString(obj);
	// }

	/**
	 * 解析请求参数
	 **/
	public static Map<String, String> decryptParamters(
			HttpServletRequest request) {
		Map<String, String> rtnMap = new HashMap<String, String>();

		try {
			// 获取get参数
			String reqString = request.getQueryString();
			System.out.println(">>>>>>>>>>>>>>>>获取的参数字符串：" + reqString);

			// if (reqString == null) {
			// //获取post参数
			// InputStream is = request.getInputStream();
			// InputStreamReader isr = new InputStreamReader(is);
			// BufferedReader br = new BufferedReader(isr);
			// // 解码POST提交的参数
			// reqString = java.net.URLDecoder.decode(br.readLine(),"UTF-8");
			// }

			if (StringUtils.isNotBlank(reqString)) {
				// 解密 Base64 + 3DES
				// String paramters = DES3Util.decode(reqString);
				//
				// // 特殊字符、中文汉字转码
				// paramters = java.net.URLDecoder.decode(paramters, "UTF-8");

				String paramters = reqString;

				System.out.println("请求参数列表：");
				String[] tmpArr = paramters.split("&");
				for (int i = 0; i < tmpArr.length; i++) {
					System.out.println("*************" + tmpArr[i]);

					String[] paramArr = tmpArr[i].split("=");
					if (paramArr.length == 1) { // 参数值为空
						rtnMap.put(paramArr[0], "");
					} else if (paramArr.length == 2) {
						rtnMap.put(paramArr[0], paramArr[1]);
					} else {

					}
				}
			}
		} catch (Exception e) {
			System.out.println("请求参数解析异常：" + e.getMessage());
			e.printStackTrace();
		}

		return rtnMap;
	}

	/**
	 * json返回客户端(加密)
	 * 
	 * @throws UnsupportedEncodingException
	 **/
	public static void responseJson(Object result, HttpServletResponse response) {
		// String encodeStr = "";
		// try {
		// logger.debug(">>>>>>>>>>>>>>>>>>>>>>返回结果加密前：" + result);
		// // 特殊字符、中文汉字转码
		// encodeStr = java.net.URLEncoder.encode(String.valueOf(result),
		// "utf-8");
		// // 加密返回json串
		// encodeStr = DES3Util.encode(encodeStr);
		//
		// logger.debug(">>>>>>>>>>>>>>>>>>>>>>返回结果加密后：" + encodeStr);
		// } catch (Exception e) {
		// logger.debug("返回结果加密异常：" + e.getMessage());
		// }

		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		try {
			PrintWriter out = response.getWriter();
			out.print(result);
			// out.print(encodeStr);
			out.flush();
			out.close();
		} catch (IOException e) {
			System.out.println("/CommonUtil/responseJson 异常:" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * json返回客户端(不加密)
	 * 
	 * @throws UnsupportedEncodingException
	 **/
	public static void responseJsonNotEncrypt(Object result,
			HttpServletResponse response) {

		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		try {
			PrintWriter out = response.getWriter();
			out.print(result);
			out.flush();
			out.close();
		} catch (IOException e) {
			System.out.println("/CommonUtil/responseJsonNotEncrypt 异常:"
					+ e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 获取随机验证码:随机产生的6位数字
	 */
	public static String getRandomCode() {
		// 获取验证码
		String randomCode = "";
		// 验证码字符个数
		int codeCount = 6;
		// 创建一个随机数生成器类
		Random random = new Random();
		// 随机产生codeCount数字的验证码
		for (int i = 0; i < codeCount; i++) {
			// 得到随机产生的验证码数字
			String strRand = String.valueOf(random.nextInt(10));
			randomCode += strRand;
		}
		return randomCode;
	}

	/**
	 * 生成订单号
	 * 
	 * 订单号格式:20140510(日期) + 1399540001193(当时系统的毫秒数)
	 * 
	 * */
	public static String createTime() {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String formatStr = sdf.format(date);// 20140508
		String dateStr = date.getTime() + "";// 1399540001193
		String now = formatStr + dateStr;

		return now;
	}

	/**
	 * 设置返回rescode、resmsg
	 * 
	 * */
	public static String setResultInfo(Map<String, Object> map, String rescode,
			String resmsg) {
		map.put("rescode", rescode);
		map.put("resmsg", resmsg);
		// 处理返回结果
		return JsonUtil.getJsonStringFromMap(map);
	}

	/**
	 * 金额判断大小
	 * 
	 * */
	public static int checkAmount(BigDecimal amount1, BigDecimal amount2) {
		// -1表示小于，0是等于，1是大于
		return amount1.compareTo(amount2);
	}

	/**
	 * 年龄判断
	 * 
	 * */
	public static int checkAge(int compareObj1, int compareObj2) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.YEAR, -compareObj2);
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		String str = sf.format(calendar.getTime());
		if (Integer.parseInt(str) == compareObj1) {
			return 0;// 等于
		} else if (Integer.parseInt(str) > compareObj1) {
			return 1;// 大于
		} else {
			return -1;// 小于
		}
	}

	/**
	 * 获取系统时间
	 * 
	 * */
	public static String getNow(String formatStr) {
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sf = new SimpleDateFormat(formatStr);
		String str = sf.format(calendar.getTime());
		return str;
	}

	/**
	 * 计算指定字符（串）在字符串里出现的次数
	 * */
	public static int countMatches(String motherStr, String subStr) {
		if (CommUtil.isBlank(motherStr) || CommUtil.isBlank(subStr)) {
			return 0;
		}
		int count = 0;
		int index = 0;
		while ((index = motherStr.indexOf(subStr, index)) != -1) {
			count++;
			index += subStr.length();
		}
		return count;
	}

	public static void main(String[] args) {
		String s = "aaa234fawe";
		String b = "a";
		System.out.println(CommUtil.countMatches(s, b));
	}
}
